package com.ys.service.sys.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ys.entity.sys.YsRole;
import com.ys.service.hr.ThrUserArchivesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.constant.AppConstant;
import com.ys.dto.AddDto;
import com.ys.dto.DtreeSqlDto;
import com.ys.dto.EditDto;
import com.ys.dto.YsTreeDto;
import com.ys.entity.sys.TsOrganizationInfo;
import com.ys.entity.sys.TsRoleInfo;
import com.ys.entity.sys.TsUserInfo;
import com.ys.mapper.sys.SysMapper;
import com.ys.mapper.sys.TsUserInfoMapper;
import com.ys.service.sys.TsUserChangeService;
import com.ys.service.sys.TsUserInfoService;
import com.ys.util.dh.DhPassUtil;
import com.ys.vo.R;

@Service("tsUserInfoService")
public class TsUserInfoServiceImpl implements TsUserInfoService {

	@Autowired
	private SysMapper sysMapper;
	@Autowired
	private TsUserInfoMapper tsUserInfoMapper;
	@Autowired
	private TsUserChangeService tsUserChangeService;
	@Autowired
	private ThrUserArchivesService thrUserArchivesService;

	
	@Override
	public R add(Map<String, Object> params) {
		if(params.get("userIdUp")!=null){
			params.put("userLeader",params.get("userIdUp"));
		}
		TsUserInfo entity = JSON.parseObject(JSON.toJSONString(params), TsUserInfo.class);
		
		// 验证所属机构
		Long orgId = entity.getOrgId();
		if (orgId == null) {
			return R.error("所属机构不能为空");
		}
		TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setId(orgId).queryFirst();
		if (tsOrganizationInfo == null) {
			return R.error("机构不存在");
		}
		
		// 验证角色
		Long roleId = entity.getRoleId();
		if (roleId == null) {
			return R.error("角色不能为空");
		}
		
		// 验证用户工号
		String userId = entity.getUserId();
		if (userId == null || userId.length() == 0) {
			return R.error("工号不能为空");
		} else if (new TsUserInfo().setUserId(userId).count() > 0) {
			return R.error("【" + userId + "】该工号已存在");
		}
		
		entity.setUserLevel(sysMapper.getEncryptUserLevel(entity.getUserId()));

		//获取用户对应的角色（岗位）信息
		YsRole ysRole = new YsRole().setId(entity.getRoleId()).queryFirst();
		if(ysRole!=null){
			// 同步1.0岗位
			TsRoleInfo tsRoleInfo = new TsRoleInfo().setRoleName(ysRole.getName()).queryFirst();
			entity.setPositionGuid(tsRoleInfo.getGuid());
		}

			
		tsUserInfoMapper.insert(entity);
		
		// 添加用户信息变动
		tsUserChangeService.add(entity, null);
		//更新用户档案信息
		thrUserArchivesService.addFromUserInfo(params);
		return R.ok(AddDto.closeAndReload());
	}


	@Override
	public R addByNew(Map<String, Object> params) {

		TsUserInfo entity = JSON.parseObject(JSON.toJSONString(params), TsUserInfo.class);

		// 验证所属机构
		Long orgId = entity.getOrgId();
		if (orgId == null) {
			return R.error("所属机构不能为空");
		}
		TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setId(orgId).queryFirst();
		if (tsOrganizationInfo == null) {
			return R.error("机构不存在");
		}

		// 验证角色
		Long roleId = entity.getRoleId();
		if (roleId == null) {
			return R.error("角色不能为空");
		}

		// 验证用户工号
		String userId = entity.getUserId();
		if (userId == null || userId.length() == 0) {
			return R.error("工号不能为空");
		} else if (new TsUserInfo().setUserId(userId).count() > 0) {
			return R.error("【" + userId + "】该工号已存在");
		}

		entity.setUserLevel(sysMapper.getEncryptUserLevel(entity.getUserId()));

		tsUserInfoMapper.insert(entity);

		// 添加用户信息变动
		tsUserChangeService.add(entity, null);
		return R.ok(AddDto.closeAndReload());
	}
	
	@Override
	public R edit(Map<String, Object> params) {
		if(params.get("userIdUp")!=null){
			params.put("userLeader",params.get("userIdUp"));
		}
		TsUserInfo entity = JSON.parseObject(JSON.toJSONString(params), TsUserInfo.class);
		TsUserInfo entityOld = new TsUserInfo().setId(entity.getId()).queryFirst();
		
		// 验证所属机构
		Long orgIdNew = entity.getOrgId();
		if (orgIdNew == null) {
			return R.error("所属机构不能为空");
		}
		TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setId(orgIdNew).queryFirst();
		if (tsOrganizationInfo == null) {
			return R.error("机构不存在");
		}
		
		// 若为旧机构负责人，则不能变动所属部门
		TsOrganizationInfo tsOrganizationInfoOld = new TsOrganizationInfo().setId(entityOld.getOrgId()).queryFirst();
		Long orgIdOld = entityOld.getOrgId();
		if (tsOrganizationInfoOld.getHeadUserId() != null
				&& tsOrganizationInfoOld.getHeadUserId().equals(entity.getUserId())
				&& !orgIdNew.equals(orgIdOld) ) {
			return R.error("该用户为所在机构负责人，无法变更组织机构");
		}
		
		// 验证角色
		Long roleId = entity.getRoleId();
		if (roleId == null) {
			return R.error("角色不能为空");
		}
		
		// 验证用户工号
		String userId = entity.getUserId();
		if (userId == null || userId.length() == 0) {
			return R.error("工号不能为空");
		} else if (!entity.getUserId().equals(entityOld.getUserId())) {
			return R.error("工号不一致");
		}

		//获取用户对应的角色（岗位）信息
		YsRole ysRole = new YsRole().setId(entity.getRoleId()).queryFirst();
		if(ysRole!=null){
			// 同步1.0岗位
			TsRoleInfo tsRoleInfo = new TsRoleInfo().setRoleName(ysRole.getName()).queryFirst();
			entity.setPositionGuid(tsRoleInfo.getGuid());
		}
		
		tsUserInfoMapper.update(entity);
		
		// 添加用户信息变动
		tsUserChangeService.add(entity, entityOld);
		//更新用户档案信息
		thrUserArchivesService.updateFromUserInfo(params);
		return R.ok(EditDto.closeAndReload());
	}
	
	@Override
	public R resetPass(Map<String, Object> params) {
		TsUserInfo entity = JSON.parseObject(JSON.toJSONString(params), TsUserInfo.class);
		
		String userId = params.get("userId").toString();
		String passNew = params.get("passNew").toString();
		String passNewConfirm = params.get("passNewConfirm").toString();
		if (!passNew.equals(passNewConfirm)) {
			return R.error("两次密码输入不一致");
		}
		
		String passEncrypt = DhPassUtil.encryptPassword(userId, passNew, AppConstant.PASSWORD_SALT);
		entity.setUserPassWord(passEncrypt);
		
		tsUserInfoMapper.update(entity);
		return R.ok("操作成功");
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) {
		if (id == null) {
			return R.error("ID不能为空");
		}
		
//		// 删除角色-按钮
//		sysMapper.deleteTrueSysRoleButtonByTsUserInfoId(id);
//		
//		// 删除按钮
//		tsUserInfoMapper.deleteTrue(id);
		
		return R.ok();
	}

	@Override
	public DtreeSqlDto dtree() {
		
		DtreeSqlDto.StatusDto status = DtreeSqlDto.StatusDto.init(200, "");

		List<DtreeSqlDto.DataDto> data = new ArrayList<DtreeSqlDto.DataDto>();
		List<TsOrganizationInfo> listTsOrganizationInfo = new TsOrganizationInfo()
				.where("A.OrgKind != 'user'")
				.setOrderby("A.OrgId asc")
				.queryList();
		// 处理部门数据，方便遍历
		Map<String, List<TsOrganizationInfo>> MAP_PGUID_LIST = new HashMap<String, List<TsOrganizationInfo>>();
		for(TsOrganizationInfo tsOrganizationInfo : listTsOrganizationInfo) {
			List<TsOrganizationInfo> listValue = MAP_PGUID_LIST.containsKey(tsOrganizationInfo.getPguid()) ? MAP_PGUID_LIST.get(tsOrganizationInfo.getPguid()) : new ArrayList<TsOrganizationInfo>();
			listValue.add(tsOrganizationInfo);
			MAP_PGUID_LIST.put(tsOrganizationInfo.getPguid(), listValue);
		}
		
		// 一级菜单
		{
			TsOrganizationInfo tsOrganizationInfoRoot = new TsOrganizationInfo().setPguid("root").queryFirst();
			String id = tsOrganizationInfoRoot.getId().toString();
			String title = tsOrganizationInfoRoot.getOrgName();
			String parentId = tsOrganizationInfoRoot.getPguid();
			
			// 二级菜单
			List<DtreeSqlDto.DataDto> children = getChildren(tsOrganizationInfoRoot, MAP_PGUID_LIST);
			
			DtreeSqlDto.DataDto dataDto1 = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), children);
			data.add(dataDto1);
		}
		return new DtreeSqlDto(status, data);
	}
	
	private List<DtreeSqlDto.DataDto> getChildren(TsOrganizationInfo current, Map<String, List<TsOrganizationInfo>> MAP_PGUID_LIST) {
		
		List<TsOrganizationInfo> listTsOrganizationInfo = MAP_PGUID_LIST.get(current.getGuid());
		List<DtreeSqlDto.DataDto> children = new ArrayList<DtreeSqlDto.DataDto>();
		if (listTsOrganizationInfo == null) {
			return null;
		} else {
			for(TsOrganizationInfo tsOrganizationInfo : listTsOrganizationInfo) {
				String id = tsOrganizationInfo.getId().toString();
				String title = tsOrganizationInfo.getOrgName();
				String parentId = tsOrganizationInfo.getPid().toString();
				
				List<DtreeSqlDto.DataDto> childrenSub = getChildren(tsOrganizationInfo, MAP_PGUID_LIST);
				DtreeSqlDto.DataDto dataDtoSub = new DtreeSqlDto.DataDto(id, title, parentId, DtreeSqlDto.DataDto.initCheckArr(null), childrenSub);
				children.add(dataDtoSub);
			}
		}
		
		return children;
	}

	@Override
	public YsTreeDto ysTree() {

		List<YsTreeDto.DataDto> data = new ArrayList<YsTreeDto.DataDto>();
		List<TsOrganizationInfo> listTsOrganizationInfo = new TsOrganizationInfo()
				.where("A.OrgKind != 'user'")
				.setOrderby("A.OrgId asc")
				.queryList();
		// 处理部门数据，方便遍历
		Map<String, List<TsOrganizationInfo>> MAP_PGUID_LIST = new HashMap<String, List<TsOrganizationInfo>>();
		for(TsOrganizationInfo tsOrganizationInfo : listTsOrganizationInfo) {
			List<TsOrganizationInfo> listValue = MAP_PGUID_LIST.containsKey(tsOrganizationInfo.getPguid()) ? MAP_PGUID_LIST.get(tsOrganizationInfo.getPguid()) : new ArrayList<TsOrganizationInfo>();
			listValue.add(tsOrganizationInfo);
			MAP_PGUID_LIST.put(tsOrganizationInfo.getPguid(), listValue);
		}
		
		// 一级菜单
		{
			TsOrganizationInfo tsOrganizationInfoRoot = new TsOrganizationInfo().setPguid("root").queryFirst();
			String id = tsOrganizationInfoRoot.getId().toString();
			String title = tsOrganizationInfoRoot.getOrgName();
			
			// 二级菜单
			List<YsTreeDto.DataDto> sub = getYsTreeSub(tsOrganizationInfoRoot, MAP_PGUID_LIST);
			
			YsTreeDto.DataDto dataDto1 = new YsTreeDto.DataDto(id, title, sub);
			data.add(dataDto1);
		}
		return new YsTreeDto( data);
	}
	
	private List<YsTreeDto.DataDto> getYsTreeSub(TsOrganizationInfo current, Map<String, List<TsOrganizationInfo>> MAP_PGUID_LIST) {
		
		List<TsOrganizationInfo> listTsOrganizationInfo = MAP_PGUID_LIST.get(current.getGuid());
		List<YsTreeDto.DataDto> children = new ArrayList<YsTreeDto.DataDto>();
		if (listTsOrganizationInfo == null) {
			return null;
		} else {
			for(TsOrganizationInfo tsOrganizationInfo : listTsOrganizationInfo) {
				String id = tsOrganizationInfo.getId().toString();
				String title = tsOrganizationInfo.getOrgName();
				
				List<YsTreeDto.DataDto> childrenSub = getYsTreeSub(tsOrganizationInfo, MAP_PGUID_LIST);
				YsTreeDto.DataDto dataDtoSub = new YsTreeDto.DataDto(id, title, childrenSub);
				children.add(dataDtoSub);
			}
		}
		
		return children;
	}

	@Override
	public R batchChangeOrg(Long orgId, String detailArr) {
		
		if (orgId == null) {
			return R.error("组织机构ID不能为空");
		}
		
		//  组织机构是否已有主管
		TsOrganizationInfo org = new TsOrganizationInfo().setId(orgId).queryFirst();
		if (org.getHeadUserId() == null || org.getHeadUserId().length() == 0) {
			return R.error("所选组织机构尚未设置主管");
		}
		
		// 验证用户是否是部门负责人
		JSONArray detailJA = JSON.parseArray(detailArr);
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			String userId = detailJO.getString("userId");
			if(new TsOrganizationInfo().setHeadUserId(userId).count() > 0) {
				return R.error("工号【" + userId + "】为部门负责人，无法变更");
			}
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long id = detailJO.getLong("id");
			
			TsUserInfo tsUserInfo = new TsUserInfo().setId(id)
					.setOrganizationid(org.getGuid())
					.setOrgId(org.getId())
					.setDeptId(org.getOrgid());
			tsUserInfoMapper.update(tsUserInfo);
		}
		return R.ok(EditDto.closeAndReload());
	}
}
